/*
 * @Author: zoufengfan
 * @Date: 2022-08-18 11:22:57
 * @LastEditTime: 2022-11-15 10:56:55
 * @LastEditors: zoufengfan
 */
import type {
  ProColumns,
  ProFieldFCRenderProps,
  ProRenderFieldPropsType,
} from '@ant-design/pro-components';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { ProProvider, ProTable } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { Button, Form, Popconfirm } from 'antd';
import React, { forwardRef, useContext, useState } from 'react';
// import DownloadBtn from '../DownloadBtn';
// import FormUpLoad from '../FormUpload';
type Params = Record<string,any>

const TableForm = ({ text, prop }: { text: any; prop: ProFieldFCRenderProps }) => {
  const [visible, setvisible] = useState(false);
  const [_idx, set_idx] = useState<number>();
  const [form]: [FormInstance<Params>] = Form.useForm<Params>();

  /**编辑行数据 */
  const handleEdit = (row: Params, idx: number) => {
    // console.log('handleEdit', row, idx);
    set_idx(idx);
    setvisible(true);
    form.setFieldsValue(row);
  };

  /**删除行数据 */
  const handleDel = (idx: number) => {
    // console.log('handleDel');
    const list = (text || []) as [];
    list.splice(idx, 1);
    prop.fieldProps.onChange?.([...list]);
  };

  /**保存行数据 */
  const _onFinish = async (values: Params) => {
    const list = text || [];
    const newRow = { _id: Date.now() + Math.random(), ...values };
    // 编辑
    if (_idx !== undefined) {
      list.splice(_idx, 1, newRow);
    } else {
      // 新增
      list.push(newRow);
    }

    prop.fieldProps.onChange?.([...list]);

    return true;
  };

  return (
    <>
      <ProTable
        rowKey="_id"
        scroll={{ x: 'max-content' }}
        pagination={false}
        dataSource={(text || []) as Params[]}
        columns={
          prop.fieldProps.columns.map((item) => {
            if (item.valueType === 'option')
              return {
                ...item,
                width: 150,
                fixed: 'right',
                render: (dom, row, idx, action) => {
                  return (
                    <>
                      <Button type="link" size="small" onClick={() => handleEdit(row, idx)}>
                        编辑
                      </Button>
                      <Popconfirm
                        placement="topRight"
                        title={'确定删除改行数据？'}
                        onConfirm={(e) => e && handleDel(idx)}
                        okText="确定"
                        cancelText="取消"
                      >
                        <Button type="link" size="small" danger>
                          删除
                        </Button>
                      </Popconfirm>
                    </>
                  );
                },
              } as ProColumns<Params, string>;
            return item;
          }) as ProColumns<Params, string>[]
        }
        search={false}
        toolBarRender={false}
      />

      <Button
        block
        type="dashed"
        onClick={() => {
          form.resetFields();
          set_idx(undefined);
          setvisible(true);
        }}
      >
        {prop.fieldProps.recordCreatorProps.creatorButtonText || '新增一行'}
      </Button>

      <BetaSchemaForm<Params>
        form={form}
        layoutType="ModalForm"
        visible={visible}
        onVisibleChange={(e) => {
          setvisible(e);
        }}
        layout="horizontal"
        rowProps={{ gutter: 16 }}
        grid={true}
        onFinish={_onFinish}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        // {...BetaSchemaFormProps}
        modalProps={{
          // onCancel,
          // destroyOnClose: true,
          width: 1000,
          title: '新增',
          maskClosable: false,
          okText: '保存',
        }}
        columns={prop.fieldProps.columns}
      />
    </>
  );
};

/**配置上的render */
const orginRender = (valueType, text, prop) => {
  const arr = (prop.proFieldKey as string).split('-');
  const dataIndex = arr[arr.length - 1];
  return prop.render(text, { [dataIndex]: text }, 0, {}, { valueType, dataIndex });
};

/**配置上的renderFormItem */
const orginFormitemRender = (valueType, text, prop) => {
  const arr = (prop.proFieldKey as string).split('-');
  const dataIndex = arr[arr.length - 1];
  return prop.renderFormItem(text, { [dataIndex]: text }, 0, {}, { valueType, dataIndex });
};

export const valueTypeMap: Record<string, ProRenderFieldPropsType> = {
  // file: {
  //   render: (text, prop) => {
  //     if (prop.render) return orginRender('file', text, prop);

  //     return (
  //       <DownloadBtn size="small" type="link" url={text}>
  //         下载
  //       </DownloadBtn>
  //     );
  //   },
  //   renderFormItem(text, prop, dom) {
  //     if (prop.renderFormItem) orginFormitemRender('file', text, prop);
  //     return <FormUpLoad {...prop.fieldProps} multiple={false} />;
  //   },
  // },
  // fileList: {
  //   render: (text, prop, dom) => {
  //     // console.log('prop', text);
  //     if (prop.render) return orginRender('fileList', text, prop);

  //     return (prop.fieldProps?.isArray ? text || [] : text?.split?.(',') || []).map(
  //       (url: string, index: number) => (
  //         <DownloadBtn size="small" type="link" url={url} key={url} style={{ marginRight: '3px' }}>
  //           文件{index + 1}
  //         </DownloadBtn>
  //       ),
  //     );
  //   },
  //   renderFormItem(text, prop, dom) {
  //     if (prop.renderFormItem) orginFormitemRender('fileList', text, prop);

  //     return <FormUpLoad {...prop.fieldProps} multiple={true} />;
  //   },
  // },
  table: {
    render: (text, prop, dom) => {
      // console.log('table ', text, prop, dom);
      // if (dom) return dom;
      if (prop.render) return orginRender('table', text, prop);

      return (
        <ProTable
          title={prop.label}
          pagination={false}
          dataSource={(text || []) as Params[]}
          columns={
            prop.fieldProps.columns.filter((el) => el.dataIndex) as ProColumns<Params, string>[]
          }
          search={false}
          toolBarRender={false}
          // scroll={{ x: 'max-content' }}//不能设置，会超出descItem的宽度
        />
      );
    },
    renderFormItem: (text, prop, dom) => {
      if (prop.renderFormItem) orginFormitemRender('table', text, prop);

      return <TableForm text={text} prop={prop} />;
    },
  },
};

/**此组件权重较高，会最后执行 */
function CustomerValueType(props: { children: any }) {
  const { children } = props;
  const values = useContext(ProProvider);

  return (
    <ProProvider.Provider
      value={{
        ...values,
        valueTypeMap,
      }}
    >
      {children}
    </ProProvider.Provider>
  );
}

export default CustomerValueType;
